
class Calendar < Pan::Component

  def initialize(owner, date=Time.now)
    @owner = owner
    @now = date
  end

  def now=(time_or_date)
    @now = time_or_date.to_time
  end

  def month_names
    %w(none Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
  end

  def month_name
    month_names[@now.month]
  end
  def today
    @now = Time.now
  end
  def prev
    @now = @now.advance(:months=>-1)
  end
  def next
    @now = @now.advance(:months=>1)    
  end

  def render_on(html)
    date = @now.at_beginning_of_month
    days = date.days_in_month

    today = Time.now.yday
    # pad
    days = (1..date.week_day).to_a.map{|ea| nil} + days
    html.div("class"=>"calendar") {
      html.heading("#{month_name} (#{@now.year})")
      html.table("cellspacing"=>"0") {
        html.tr {
          ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].each { |weekday|
            html.th { html.text(weekday) }
          }
        }
        days.in_groups_of(7) {|slice|
          html.tr {
            html.th("class"=>"week") {
              html.text(slice.compact[-1].week)
            }
            slice.each {|day|
              if day 
                # @owner.render_cell(day,html,day.yday == today)
                html.td("class"=>day.yday == today ? "today" : "day-#{day.week_day}") {
                  @html = html
                  @owner.render_cell(day,self,day.yday == today)
                }
              else
                html.td("class"=>"day-outside") { 
                  html.nbsp 
                }
              end
            }
          }
        }
      }
    }
    html.div("class"=>"bottom-shadow") { }
  end

  def content_for_cell
    yield @html
    @html = nil
  end
end
